package com.llq.ui;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.List;

import org.junit.Assert;
import org.junit.Test;

import com.llq.studentinfo.Student;

public class StudentUITest {

	static private final String name = "Li Qiang";

	private void setup(StringBuilder expectedOutput, StringBuilder input) {
		expectedOutput.append(StudentUI.MENU);
		input.append(line(StudentUI.ADD_OPTION));
		expectedOutput.append(StudentUI.NAME_PROMPT);
		input.append(line(name));
		expectedOutput.append(line(StudentUI.ADDED_MESSAGE));
		expectedOutput.append(StudentUI.MENU);
		input.append(line(StudentUI.QUIT_OPTION));
	}

	@Test
	public void createStudentTest() throws IOException {
		StringBuilder expectedOutput = new StringBuilder();
		StringBuilder input = new StringBuilder();
		setup(expectedOutput, input);
		byte[] buffer = input.toString().getBytes();

		InputStream inputStream = new ByteArrayInputStream(buffer);
		OutputStream outputStream = new ByteArrayOutputStream();

		InputStream consoleIn=System.in;
		OutputStream consoleOut=System.out;
		
		System.setIn(inputStream);
		System.setOut(new PrintStream(outputStream));

		try {
			StudentUI ui = new StudentUI();
			ui.run();
			Assert.assertEquals(expectedOutput.toString(), outputStream
					.toString());
			assertStudents(ui.getAddedStudents());
		} finally {
			System.setIn(consoleIn);
			System.setOut(new PrintStream(consoleOut));
		}

		// InputStream inputStream = new ByteArrayInputStream(buffer);
		// BufferedReader reader = new BufferedReader(new InputStreamReader(
		// inputStream));
		//
		// OutputStream outputStream = new ByteArrayOutputStream();
		// BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
		// outputStream));
		//
		// StudentUI ui = new StudentUI(reader, writer);
		// ui.run();
		//
		// Assert.assertEquals(expectedOutput.toString(),
		// outputStream.toString());
		// assertStudents(ui.getAddedStudents());
	}

	private void assertStudents(List<Student> students) {
		Assert.assertEquals(1, students.size());
		Student student = students.get(0);
		Assert.assertEquals(name, student.getName());
	}

	private String line(String input) {
		return String.format("%s%n", input);
	}
	
	
}
